#include "gamewidget.h"
#include <QRandomGenerator>
#include <QApplication>

GameWidget::GameWidget(QWidget *parent) : QWidget(parent) {
    setFocusPolicy(Qt::StrongFocus);
    setFixedSize(800, 600);
    setFocusPolicy(Qt::StrongFocus);
    gameTimer = new QTimer(this);
    connect(gameTimer, &QTimer::timeout, this, &GameWidget::updateGame);
}

void GameWidget::startGame() {
    resetGame();
    gameTimer->start(50); // 启动定时器
    setFocus(); // 确保获得焦点
}

void GameWidget::resetGame() {
    playerX = width() / 2;
    bullets.clear();
    enemies.clear();
    score = 0;
    gameOver = false;
}

void GameWidget::paintEvent(QPaintEvent *) {
    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);

    // 绘制玩家（飞机）
    painter.setBrush(Qt::green);
    painter.drawRect(playerX, height() - 50, 30, 30);

    // 绘制子弹和敌机（简化为矩形）
    painter.setBrush(Qt::yellow);
    for (auto &b : bullets) {
        if (b.active) painter.drawRect(b.x, b.y, 5, 10);
    }

    painter.setBrush(Qt::red);
    for (auto &e : enemies) {
        if (e.active) painter.drawRect(e.x, e.y, 30, 30);
    }

    // 显示分数
    painter.setPen(Qt::white);
    painter.drawText(10, 20, QString("得分: %1").arg(score));
}

void GameWidget::keyPressEvent(QKeyEvent *event) {
    if (gameOver) return;

    switch (event->key()) {
        case Qt::Key_A:
            playerX = qMax(0, playerX - 20);
            break;
        case Qt::Key_D:
            playerX = qMin(width() - 30, playerX + 20); // 30为玩家宽度
            break;
        case Qt::Key_Space:
            bullets.push_back({playerX + 15, height() - 60, true});
            break;
        case Qt::Key_Q:
            QApplication::quit(); // 按 Q 键退出游戏
            break;
    }
    update(); // 触发重绘
}

void GameWidget::updateGame() {
    // 随机生成敌机
    if (QRandomGenerator::global()->bounded(100) < 5) { // 5% 的概率生成敌机
        int x = QRandomGenerator::global()->bounded(width() - 30); // 随机位置
        enemies.push_back({x, 0, 0, true});
    }

    // 移动子弹
    for (auto &b : bullets) {
        if (b.active) {
            b.y -= 10; // 子弹向上移动
            if (b.y < 0) {
                b.active = false; // 子弹超出屏幕，标记为不活跃
            }
        }
    }

    // 移动敌机
    for (auto &e : enemies) {
        if (e.active) {
            e.y += 5; // 敌机向下移动
            if (e.y > height()) {
                e.active = false; // 敌机超出屏幕，标记为不活跃
                score++; // 躲避敌机，增加分数
            }
        }
    }

    // 碰撞检测
    for (auto &b : bullets) {
        if (b.active) {
            for (auto &e : enemies) {
                if (e.active) {
                    if (b.x >= e.x && b.x <= e.x + 30 && b.y >= e.y && b.y <= e.y + 30) {
                        // 子弹和敌机碰撞
                        b.active = false;
                        e.active = false;
                        score += 5; // 增加5分
                    }
                }
            }
        }
    }

    // 移除不活跃的子弹和敌机
    auto newEndBullets = std::remove_if(bullets.begin(), bullets.end(), [](const Bullet &b) { return !b.active; });
    bullets.erase(newEndBullets, bullets.end());

    auto newEndEnemies = std::remove_if(enemies.begin(), enemies.end(), [](const Enemy &e) { return !e.active; });
    enemies.erase(newEndEnemies, enemies.end());

    update(); // 触发重绘
}
